package org.zwy.gradetrack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.Major;
import org.zwy.gradetrack.service.MajorService;

import java.util.List;

/**
 * 专业管理控制器
 */
@RestController
@RequestMapping("/api/majors")
public class MajorController {

    @Autowired
    private MajorService majorService;

    /**
     * 获取专业列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER','GRADUATE')")
    public Result<List<Major>> getMajorList() {
        List<Major> majors = majorService.list();
        return Result.success(majors);
    }

    /**
     * 创建专业
     */
    @PostMapping
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Major> createMajor(@RequestBody Major major) {
        // 检查专业代码是否已存在
        if (majorService.lambdaQuery()
                .eq(Major::getMajorCode, major.getMajorCode())
                .exists()) {
            return Result.error(400, "专业代码已存在");
        }

        // 保存专业信息
        majorService.save(major);
        return Result.success(major);
    }

    /**
     * 更新专业
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Major> updateMajor(@PathVariable Long id, @RequestBody Major major) {
        // 检查专业是否存在
        if (!majorService.lambdaQuery()
                .eq(Major::getId, id)
                .exists()) {
            return Result.error(404, "专业不存在");
        }

        // 检查专业代码是否重复
        if (majorService.lambdaQuery()
                .eq(Major::getMajorCode, major.getMajorCode())
                .ne(Major::getId, id)
                .exists()) {
            return Result.error(400, "专业代码已存在");
        }

        // 更新专业信息
        major.setId(id);
        majorService.updateById(major);
        return Result.success(major);
    }

    /**
     * 删除专业
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Void> deleteMajor(@PathVariable Long id) {
        // 检查专业是否存在
        if (!majorService.lambdaQuery()
                .eq(Major::getId, id)
                .exists()) {
            return Result.error(404, "专业不存在");
        }

        // 删除专业
        majorService.removeById(id);
        return Result.success();
    }

    /**
     * 获取专业详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<Major> getMajorDetail(@PathVariable Long id) {
        Major major = majorService.getById(id);
        if (major == null) {
            return Result.error(404, "专业不存在");
        }
        return Result.success(major);
    }
} 